package org.zhq.server;

import org.zhq.Foo;
import org.zhq.box.StringReceivePacket;
import org.zhq.handle.ConnectorHandler;
import org.zhq.handle.ConnectorStringPacketChain;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhengquan
 * @date 2019/2/24
 */
public class Group {

    private final String name;

    private final GroupMessageAdapter adapter;

    private final List<ConnectorHandler> members = new ArrayList<>();

    Group(String name, GroupMessageAdapter adapter) {
        this.name = name;
        this.adapter = adapter;
    }

    String getName() {
        return name;
    }

    boolean addMember(ConnectorHandler handler) {
        synchronized (members) {
            if (!members.contains(handler)) {
                members.add(handler);
                handler.getStringPacketChain()
                        .appendLast(new ForwardConnectorStringPacketChain());
                System.out.println("Group[" + name + "] add new member" + handler.getClientInfo());
                return true;
            }
            return false;
        }
    }

    boolean removeMember(ConnectorHandler handler) {
        synchronized (members) {
            if (members.remove(handler)) {
                handler.getStringPacketChain()
                        .remove(ForwardConnectorStringPacketChain.class);
                System.out.println("Group[" + name + "] leave a member" + handler.getClientInfo());
                return true;
            }
            return false;
        }
    }


    private class ForwardConnectorStringPacketChain extends ConnectorStringPacketChain {

        @Override
        protected boolean consume(ConnectorHandler handler, StringReceivePacket stringReceivePacket) {
            String string = stringReceivePacket.entity();
            if (!string.startsWith(Foo.COMMAND_GROUP_PREFIX + Foo.COMMAND_GROUP_SEND)) {
                return false;
            }
            string = string.substring(Foo.COMMAND_GROUP_PREFIX.length());
            String[] s = string.split(" ");
            String groupName = s[1];
            String message = string.substring(Foo.COMMAND_GROUP_SEND.length() + groupName.length() + 1);
            if (name.equals(groupName)) {
                String wrapMessage = "Group:[" + name + "]from[" + handler.getKey() + "]:" + message;
                synchronized (members) {
                    for (ConnectorHandler member : members) {
                        if (member.equals(handler)) {
                            continue;
                        }
                        adapter.sendMessageToClient(member, wrapMessage);
                    }
                    return true;
                }
            }
            return false;
        }
    }

    interface GroupMessageAdapter {
        void sendMessageToClient(ConnectorHandler handler, String msg);
    }
}
